﻿using EnvDTE;
using Inaction.UI.ComponentModel.Design;
using Inaction.UI.Settings;
using System;
using System.ComponentModel.Design;
using System.IO;
using System.Windows.Forms;

namespace Inaction.UI
{
    internal sealed class BarManagerDesigner : DevExpress.XtraBars.Design.BarManagerDesigner
    {
        DevExpress.Utils.WaitDialogForm waitDialog = null;

        [ThreadStatic]
        internal static Inaction.UI.BarManager WorkingBarManager;

        public BarManagerDesigner()
        {
            waitDialog = new DevExpress.Utils.WaitDialogForm("", "系统提示...");
            waitDialog.Hide();
        }
        protected override void CreateDefaultBars()
        {
            try
            {
                waitDialog.Caption = "正在初始化,请稍等...";
                waitDialog.Show();
                Application.DoEvents();
                Manager.ForceLinkCreate();
                (Manager as Inaction.UI.BarManager).CreateItems();
                Manager.ForceInitialize();
            }
            catch (Exception ex)
            {
                var f = new Settings.SettingInfoForm(ex.GetMessage(true));
                f.ShowDialog();
            }
            finally
            {
                waitDialog.Hide();
            }
        }

        #region 设计时菜单
        protected override void RegisterActionLists(DesignerActionListCollection list) { }
        protected override void CreateConvertToRibbonVerb() { }
        protected override void CreateVerbs()
        {
            base.CreateVerbs();
            this.Verbs.Add(new DesignerVerb("连接数据库", new EventHandler(ConnecteDb)));
            this.Verbs.Add(new DesignerVerb("设置控件TabIndex", new EventHandler(SetControlTabIndex)));
            this.Verbs.Add(new DesignerVerb("设置控件属性", new EventHandler(SetControlEvent)));
            this.Verbs.Add(new DesignerVerb("设置外键关联", new EventHandler(SetForeignKeyControlEvent)));
            this.Verbs.Add(new DesignerVerb("清除未使用的组件", new EventHandler(ClearUnBindBindings)));
        }

        #region 自定义菜单的事件

        EnvDTE.DTE dte;
        internal EnvDTE.DTE Dte
        {
            get
            {
                if (dte == null) dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
                return dte;
            }
        }
        internal string OutputPath
        {
            get
            {
                var p = GetActiveProject(Dte);
                var temp = p.ConfigurationManager.Item(1);
                var outPutPath = System.IO.Path.Combine(new FileInfo(p.FullName).Directory + "\\"
                    + temp.Properties.Item("OutputPath").Value.ToString());
                outPutPath = System.IO.Path.GetFullPath(outPutPath);
                return outPutPath;
            }
        }
        private void ConnecteDb(object obj, EventArgs e)
        {
            Inaction.Database.DesignTimeProvider.ConnecteDb();
        }
        private void SetControlTabIndex(object obj,EventArgs e)
        {
            var barManager = Manager as Inaction.UI.BarManager;
            string message = string.Empty;
            var verb = obj as DesignerVerb;
            try
            {
                WorkingBarManager = barManager;
                waitDialog.Caption = "正在设置控件属性,请稍等...";
                waitDialog.Show();
                Application.DoEvents();
                ComponentCache.InitCache();
                LayoutGroupSetting.SetRootGroup();
                ControlSetting.SetTabIndex(barManager.Form.Controls, ref message);
                waitDialog.Hide();
                var f = new SettingInfoForm(message);
                f.Text = verb.Text;
                f.BringToFront();
                f.ShowDialog();
            }
            catch (Exception ex)
            {
                waitDialog.Hide();
                var f = new SettingInfoForm(ex.GetMessage(true));
                f.Text = verb.Text;
                f.BringToFront();
                f.ShowDialog();
            }
            finally
            {
            }
        }
        private void SetForeignKeyControlEvent(object obj,EventArgs e)
        {
             string message = string.Empty;
             try
             {
                 var path = OutputPath;
                 Inaction.DbProvider.SetInstance(Inaction.Database.DesignTimeProvider.Instance.Provider);
                 WorkingBarManager = Manager as Inaction.UI.BarManager;
                 waitDialog.Caption = "正在设置外键关系控件,请稍等..." + Environment.NewLine + path;
                 waitDialog.Show();
                 ComponentCache.InitCache();
                 EnumHelper.InitEnums();
                 TableClassTypeHelper.Init(path);
                 ForeignKeyLueSetting.SetProperties();
                 Application.DoEvents();
                 waitDialog.Hide();
                 MessageBox.Show("设置完成");
             }
             catch (Exception ex)
             {
                 waitDialog.Hide();
                 var f = new SettingInfoForm(ex.GetMessage(true));
                 f.BringToFront();
                 f.ShowDialog();
             }
             finally
             {
             }
        }

        private void SetControlEvent(object obj, EventArgs e)
        {
            var barManager = Manager as Inaction.UI.BarManager;
            string message = string.Empty;
            var verb = obj as DesignerVerb;
            try
            {
                var path = OutputPath;
                message += path + Environment.NewLine;
                message += "----------------------------------" + Environment.NewLine;
                Inaction.DbProvider.SetInstance(Inaction.Database.DesignTimeProvider.Instance.Provider);
                WorkingBarManager = barManager;
                waitDialog.Caption = "正在设置控件属性,请稍等...";
                waitDialog.Show();
                Application.DoEvents();
                ComponentCache.InitCache();
                EnumHelper.InitEnums();
                TableClassTypeHelper.Init(path);
                ControlSetting.SetProperties(barManager.Form.Controls, ref message);
                waitDialog.Hide();
                var f = new SettingInfoForm(message);
                f.Text = verb.Text;
                f.BringToFront();
                f.ShowDialog();
            }
            catch (Exception ex)
            {
                waitDialog.Hide();
                var f = new SettingInfoForm(ex.GetMessage(true));
                f.Text = verb.Text;
                f.BringToFront();
                f.ShowDialog();
            }
            finally
            {
            }
        }
        private void ClearUnBindBindings(object obj, EventArgs e)
        {
            try
            {
                waitDialog.Caption = "正在清除未使用的组件,请稍等...";
                waitDialog.Show();
                Application.DoEvents();
                var barManager = Manager as BarManager;
                var list = barManager.Container.Components.GetEnumerator();
                while (list.MoveNext())
                {
                    if (list.Current is BindingInfo)
                    {
                        if (barManager.BindingInfos == null || !barManager.BindingInfos.Contains(list.Current as BindingInfo))
                        {
                            barManager.Container.Remove(list.Current as BindingInfo);
                        }
                    }
                }
                waitDialog.Hide();
                MessageBox.Show("清除完成！");
            }
            catch (Exception ex)
            {
                var f = new Settings.SettingInfoForm(ex.GetMessage(true));
                f.ShowDialog();
            }
            finally
            {
                waitDialog.Hide();
            }
        }
        #endregion
        internal static Project GetActiveProject(DTE dte)
        {
            Array activeSolutionProjects = dte.ActiveSolutionProjects as Array;
            if (activeSolutionProjects != null && activeSolutionProjects.Length > 0)
            {
                return activeSolutionProjects.GetValue(0) as Project;
            }
            else
            {
                return ((EnvDTE.DTE)(dte)).ActiveWindow.Project;
            }
        }
        #endregion
    }
}

